package mi.payment.utils.props;

import android.content.Context;
import android.os.Environment;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import mi.payment.MyApplication;
import mi.payment.settings.MerchantSettingsOperation;
import mi.payment.settings.NetworkDataOperations;
import mi.payment.settings.OfflineTransactionOperation;
import mi.payment.settings.SalesSlipPrintSettingsOperation;
import mi.payment.settings.SecurityPasswordSettingsOperation;
import mi.payment.settings.SettlementTransactionOperation;
import mi.payment.settings.SystemParamsOperation;
import mi.payment.settings.TerminalKeyDataOperations;
import mi.payment.settings.TransactionInputPwdOperation;
import mi.payment.settings.TransactionOtherOperation;
import mi.payment.settings.TransactionSwitchOperation;

/**
 * 加载默认配置工具
 * Created by xurong on 2017/2/16.
 */

public class LoadConfigFileUtils {
    private Context mContext;
    /**
     * 默认配置文件路径
     */
    public static final String CONFIGFILEPATH = Environment.getExternalStorageDirectory().getAbsolutePath();
    /**
     * 默认配置文件名
     */
    public static final String CONFIGFILENAME = "DefaultConfig.properties";

    private static LoadConfigFileUtils mLoadConfigFileUtils;

    private LoadConfigFileUtils() {
        mContext = MyApplication.getInstance();
    }

    public static LoadConfigFileUtils getInstance() {
        if (mLoadConfigFileUtils == null) {
            mLoadConfigFileUtils = new LoadConfigFileUtils();
        }
        return mLoadConfigFileUtils;
    }

    /**
     * 加载默认配置文件
     */
    public void loadingConfigFile() {
        Properties prop = new Properties();
        InputStream in = null;
        try {
            File file = new File(CONFIGFILEPATH, CONFIGFILENAME);
            if (!file.exists()) {
                return;
            }
            // 读取属性文件properties
            in = new FileInputStream(file);
            // 加载属性列表
            prop.load(in);
            //商户管理设置
            loadMerManagerSettings(prop);
            //网络参数设置
            loadNetworkParamSettings(prop);
            //离线交易控制
            loadOfflineTransactionSettings(prop);
            //签购单打印设置
            loadSalesSlipPrintSettings(prop);
            //安全密码设置
            loadSecurityPasswordSettings(prop);
            //交易结算状态配置
            loadSettlementTransaction(prop);
            //交易管理设置
            loadSystemParamsSettings(prop);
            //终端密钥管理实体类
            loadTerminalKeyManagementBean(prop);
            //交易密码
            loadTransactionInputPsd(prop);
            //其他交易控制
            loadTransactionOtherSettings(prop);
            //交易开关设置
            loadTransactionSwitchSetting(prop);

            //删除配置文件
            if (in != null) {
                in.close();
            }

            if (file.exists() && file.isFile()) {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 商户管理设置
     */
    private void loadMerManagerSettings(Properties prop) throws Exception {
        MerchantSettingsOperation msOpertion = MerchantSettingsOperation.getInstance();
        msOpertion.init(getString(prop, "merchantNum"),
                getString(prop, "merchantName"),
                getString(prop, "merchantEnglishName"),
                getString(prop, "terminalNum"));
    }

    /**
     * 网络参数设置
     *
     * @param prop
     * @throws Exception
     */
    private void loadNetworkParamSettings(Properties prop) throws Exception {
        NetworkDataOperations mpsOptions = NetworkDataOperations.getInstance();
        mpsOptions.init(
                getString(prop, "tpdu"),
                getString(prop, "hostIpAddress"),
                getString(prop, "hostPort"),
                getString(prop, "communicationTimeout"),
                PropsUtil.getBoolean(prop, "automaticGetIp"),
                getString(prop, "spareHostIpAddress"),
                getString(prop, "spareHostPort"),
                PropsUtil.getInt(prop, "transactionRepeatNum"),
                PropsUtil.getInt(prop, "connectionMode"),
                PropsUtil.getInt(prop, "networkDefaultConfiguration"),
                PropsUtil.getBoolean(prop, "networkInterventionFunction"),
                PropsUtil.getBoolean(prop, "dns"));
    }

    /**
     * 离线交易控制
     *
     * @param prop
     * @throws Exception
     */
    private void loadOfflineTransactionSettings(Properties prop) throws Exception {
        OfflineTransactionOperation otOption = OfflineTransactionOperation.getInstance();
        otOption.init(
                PropsUtil.getInt(prop, "offlinePushCount"),
                PropsUtil.getInt(prop, "automaticallyNumber"),
                PropsUtil.getBoolean(prop, "smallPaymentWay"));
    }

    /**
     * 签购单打印设置
     *
     * @param prop
     * @throws Exception
     */
    private void loadSalesSlipPrintSettings(Properties prop) throws Exception {
        SalesSlipPrintSettingsOperation sspsOperation = SalesSlipPrintSettingsOperation.getInstance();
        sspsOperation.init(
                PropsUtil.getInt(prop, "rise"),
                getString(prop, "hotline"),
                getString(prop, "riseString"),
                getString(prop, "printReceiptSingleNum"),
                PropsUtil.getBoolean(prop, "acquiringBankPrintChinese"),
                PropsUtil.getBoolean(prop, "issuingBankPrintChinese"),
                PropsUtil.getBoolean(prop, "salesSlipPrintChinese"));
    }

    /**
     * 安全密码设置
     *
     * @param prop
     * @throws Exception
     */
    private void loadSecurityPasswordSettings(Properties prop) throws Exception {
        SecurityPasswordSettingsOperation spOperation = SecurityPasswordSettingsOperation.getInstance();
        spOperation.saveSecurityPassword(getString(prop, "securityPassword"));
    }

    /**
     * 交易结算状态配置
     */
    private void loadSettlementTransaction(Properties prop) throws Exception {
        SettlementTransactionOperation stOperation = SettlementTransactionOperation.getInstance();
        stOperation.saveAutomaticSignOut(PropsUtil.getBoolean(prop, "isAutomaticSignOut"));
    }

    /**
     * 系统参数设置
     */
    private void loadSystemParamsSettings(Properties prop) throws Exception {
        SystemParamsOperation spOperation = SystemParamsOperation.getInstance();
        spOperation.init(
                getString(prop, "serialNumStart"),
                getString(prop, "batchNumStart"),
                PropsUtil.getInt(prop, "purchaseOrderStyle"),
                PropsUtil.getInt(prop, "correctFrequency"),
                PropsUtil.getInt(prop, "transactionNumber"),
                PropsUtil.getBoolean(prop, "printNegative"),
                PropsUtil.getInt(prop, "nonConnection"),
                PropsUtil.getBoolean(prop, "stateSecret"),
                PropsUtil.getBoolean(prop, "shieldAuthorizationCard"),
                PropsUtil.getInt(prop, "nonConnectionChoice"),
                PropsUtil.getBoolean(prop, "eCashVisaExemption"));
    }

    /**
     * 终端密钥管理实体类
     */
    private void loadTerminalKeyManagementBean(Properties prop) throws Exception {
        TerminalKeyDataOperations tkdOperation = TerminalKeyDataOperations.getInstance();
        tkdOperation.init(
                getString(prop, "terialKeyIndex"),
                getString(prop, "KEK"),
                getString(prop, "des"),
                PropsUtil.getInt(prop, "icImportKey"));
    }

    /**
     * 交易密码
     */
    private void loadTransactionInputPsd(Properties prop) throws Exception {
        TransactionInputPwdOperation ttpOperation = TransactionInputPwdOperation.getInstance();
        ttpOperation.init(
                PropsUtil.getBoolean(prop, "consumptionRevokePsd"),
                PropsUtil.getBoolean(prop, "fieldAuthRevokePsd"),
                PropsUtil.getBoolean(prop, "fieldAuthCompleteRevokePsd"),
                PropsUtil.getBoolean(prop, "fieldAuthCompleteReqPsd"));
    }

    /**
     * 其他交易控制
     */
    private void loadTransactionOtherSettings(Properties prop) throws Exception {
        TransactionOtherOperation toOperation = TransactionOtherOperation.getInstance();
        toOperation.init(
                PropsUtil.getBoolean(prop, "inputDirectorPsd"),
                PropsUtil.getBoolean(prop, "inputCardNum"),
                PropsUtil.getBoolean(prop, "defaultTransaction"),
                PropsUtil.getInt(prop, "maximumReturnAmount"));
    }

    /**
     * 交易开关设置
     */
    private void loadTransactionSwitchSetting(Properties prop) throws Exception {
        TransactionSwitchOperation tsOperation = TransactionSwitchOperation.getInstance();
        tsOperation.init(
                PropsUtil.getBoolean(prop, "consumption"),
                PropsUtil.getBoolean(prop, "consumptionRevoke"),
                PropsUtil.getBoolean(prop, "returnGoods"),
                PropsUtil.getBoolean(prop, "queryBalance"),
                PropsUtil.getBoolean(prop, "fieldAuth"),
                PropsUtil.getBoolean(prop, "fieldAuthRevoke"),
                PropsUtil.getBoolean(prop, "fieldAuthReq"),
                PropsUtil.getBoolean(prop, "fieldAuthCompleteRevocationNotice"),
                PropsUtil.getBoolean(prop, "fieldAuthCompleteRevocation"));
    }

    /**
     * 根据key获取Value 解决中文乱码的问题
     *
     * @param prop
     * @param key
     * @return
     * @throws Exception
     */
    public static String getString(Properties prop, String key) throws Exception {
        return new String(prop.getProperty(key).getBytes("ISO8859-1"), "UTF-8");
    }
}
